package com.heima.behavior.service.impl;

import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApLikesBehaviorService;
import com.heima.model.behavior.dtos.LikesBehaviorDTO;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApLikesBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author zx
 * @date 2021/11/27 21:15
 */
@Service
@Slf4j
public class ApLikesBehaviorServiceImpl implements ApLikesBehaviorService {

    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;

    @Autowired
    MongoTemplate mongoTemplate;

    /**
     * 点赞行为
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(LikesBehaviorDTO dto) {

        // 1. 校验参数
        // 1.1点赞需要登录
        ApUser user = AppThreadLocalUtils.getUser();
        if(user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //1.2 校验文章id不能为空     使用注解校验
        // 1.3  校验点赞方式 只能是0 或 1  使用注解校验

        // 2. 查询行为实体
        ApBehaviorEntry BE = apBehaviorEntryService.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());
        if (BE == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        // 3. 查询是否有该行为实体的点赞记录 如果是点赞并且有记录 提示请勿重复点赞
        Query query = Query.query(Criteria.where("entryId").is(BE.getId()).and("articleId").is(dto.getArticleId()));

        ApLikesBehavior fans = mongoTemplate.findOne(query, ApLikesBehavior.class);

        if(dto.getOperation().intValue() == 0 && fans!=null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"请勿重复点赞");
        }

        // 4. 点赞或取消点赞
        if(dto.getOperation().intValue() == 0){

            // 点赞
            fans = new ApLikesBehavior();

            fans.setEntryId(BE.getId());
            fans.setArticleId(dto.getArticleId());
            fans.setType((short)0);
            fans.setOperation((short)0);
            fans.setCreatedTime(new Date());

            mongoTemplate.save(fans);
        }else {
            // 取消点赞
            mongoTemplate.remove(query,ApLikesBehavior.class);
        }
        return ResponseResult.okResult();
    }
}
